package evolution.cli;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import evolution.Directory;
import evolution.Resource;
import evolution.ResourceException;
import evolution.ResourceVisitor;


public class TransientDirectory implements Directory
{
	private final String name;

	private Map<String, Resource> members = new HashMap<String, Resource>();

	private FileSystemDirectory delegate;

	private Directory parent;

	private final long lastModified;

	public TransientDirectory(String name, long lastModified)
	{
		this.name = name;
		this.lastModified = lastModified;
	}

	public void addMember(Resource resource) throws ResourceException
	{
		if (delegate != null)
		{
			delegate.addMember(resource);
		}
		else
		{
			members.put(resource.getName(), resource);
		}
	}

	public Resource getMember(String name)
	{
		if (delegate != null)
		{
			return delegate.getMember(name);
		}
		else
		{
			return members.get(name);
		}
	}

	public String getName()
	{
		if (delegate != null)
		{
			return delegate.getName();
		}
		else
		{
			return name;
		}
	}

	public void deleteMember(String name)
	{
		throw new UnsupportedOperationException("TODO");
	}

	public Iterator<Resource> iterator()
	{
		if (delegate != null)
		{
			return delegate.iterator();
		}
		else
		{
			return members.values().iterator();
		}
	}

	public void setParent(Directory parent)
	{
		if (delegate != null)
		{
			delegate.setParent(parent);
		}
		else
		{
			this.parent = parent;
		}
	}

	public void etherealize(FileSystemDirectory delegate) throws ResourceException
	{
		delegate.mkdir();
		this.delegate = delegate;
		if (parent != null)
		{
			delegate.setParent(parent);
		}
		for (Resource r : this)
		{
			delegate.addMember(r);
		}
		members.clear();
	}

	@Override
    public String toString()
	{
		return getName();
	}

	public String getPath()
	{
		if (delegate != null)
		{
			return delegate.getPath();
		}
		else
		{
			if (parent != null)
			{

				String parentPath = parent.getPath();
				if (parentPath.equals("/"))
				{
					return "/" + getName();
				}
				else
				{
					return parentPath + "/" + getName();
				}
			}
			else
			{
				return getName();
			}
		}
	}

	public long getLastModifiedTime()
	{
		return lastModified;
	}

	public void accept(ResourceVisitor visitor)
	{
		throw new UnsupportedOperationException("TODO");
	}

}
